package com.comac.print.component.app.command.printSheetExe;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.cola.dto.SingleResponse;
import com.comac.print.component.app.common.PrintCommon;
import com.comac.print.component.app.domain.gateway.constant.CommonConstant;
import com.comac.print.component.app.domain.gateway.enums.*;
import com.comac.print.component.app.dto.*;
import com.comac.print.component.app.utils.FoFileOperateUtil;
import com.comac.print.component.app.utils.ImageUtils;
import com.google.zxing.BarcodeFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.util.*;


/**
 * @author yy
 */
@Component
@Slf4j
public class FollowSheetExe {


    @Autowired
    private FoFileOperateUtil foFileOperateUtil;

    final String IMAGE_HEAD="data:image/jpg;base64,";

    public SingleResponse printFollowSheet(PrintCommon printCommon) throws Exception {
        //TODO 打印组件将模板和数据结合生成新的文件
        return SingleResponse.of(foFileOperateUtil.exportToFile(printCommon.getData(),printCommon.getMasterPlateDTO().getMpUrl(),printCommon.getSystemId(), printCommon.getBussinessId()));
    }


    public SingleResponse printFollowSheet(FoSourceDTO foSourceDTO ,String mpUrl) throws Exception {
        FollowSheetDTO followSheetDTO = new FollowSheetDTO();
        if (foSourceDTO == null){
            return SingleResponse.buildFailure("-1","查询工单为空!");
        }
        // 制造部门
        FoMfgDeptEnum foMfgDeptEnumByCode = FoMfgDeptEnum.getFoMfgDeptEnumByCode(foSourceDTO.getMfgDept());
        if(foMfgDeptEnumByCode != null){
            followSheetDTO.setDept(foMfgDeptEnumByCode.getDescription());
        }
        // 订单号
        followSheetDTO.setOrderNum(foSourceDTO.getOrderNum());
        followSheetDTO.setSerNo(foSourceDTO.getSerNo());
        followSheetDTO.setPartNo(foSourceDTO.getPartNo());
        followSheetDTO.setChgltr(foSourceDTO.getChgltr());
        followSheetDTO.setQty(foSourceDTO.getQty());
        followSheetDTO.setPartName(foSourceDTO.getPartName());
        followSheetDTO.setEff(foSourceDTO.getFlyNo());
        followSheetDTO.setReleaseDate(foSourceDTO.getReleaseDate());
        // 参考草图/图形
        List<FoAttachmentDTO> foSketch = foSourceDTO.getFoSketch();
        if (CollectionUtil.isNotEmpty(foSketch)){
            followSheetDTO.setChart(IMAGE_HEAD+ImageUtils.image2Base64(foSketch.get(0).getUrl()));
        }
        //所需材料
        FoMaterialDTO foMaterialDTO = Optional.of(foSourceDTO.getFoRequiredMaterial()).orElse(new FoMaterialDTO());
        FoRequiredMaterialDTO foRequiredMaterialDTO = new FoRequiredMaterialDTO();
        BeanUtils.copyProperties(foMaterialDTO,foRequiredMaterialDTO);
        followSheetDTO.setFoRequiredMaterial(foRequiredMaterialDTO);
        // 工序-基本信息
        List<FoWorkSeqDTO> foWorkDOs = foSourceDTO.getFoWorkSeqList();

        // 加工状态目视表
        List<VisualDTO> visualDTOList = new ArrayList<>();

        // 热处理工序
        List<HeatWorkDTO> heatWorkList =new ArrayList<>();
        boolean hotFlg =false;
        if (ObjectUtil.isNotEmpty(foWorkDOs)) {
            for (int i = 0; i < foWorkDOs.size(); i++) {
                VisualDTO visualDTO =new VisualDTO();
                // 可选工序
                if (!CommonConstant.LINE_THROUGH.equals(foWorkDOs.get(i).getOptionalInstruction())){
                    visualDTO.setWorkNo(foWorkDOs.get(i).getSequence()+CommonConstant.LINE_THROUGH +foWorkDOs.get(i).getOptionalInstruction());
                } else {
                    visualDTO.setWorkNo(foWorkDOs.get(i).getSequence());
                }
                visualDTO.setRemarks(foWorkDOs.get(i).getRemark());

                FoWorkStatusEnum foWorkStatusEnum = FoWorkStatusEnum.getFoWorkStatusEnumByCode(foWorkDOs.get(i).getStatus());
                if (FoWorkStatusEnum.DONE.getCode().equals(foWorkStatusEnum.getCode())){
                    visualDTO.setStatus( "√" );
                } else {
                    visualDTO.setStatus( "" );
                }

                visualDTO.setWorkRemarks(foWorkDOs.get(i).getRemark());

                StringBuffer remark = new StringBuffer();
                // 备注 工序上设置DMIR、FAI的要在备注上标识
                if (foWorkDOs.get(i).getDmirFlag()>0){
                    remark.append("DMIR");
                    remark.append("\n");
                }
                if (StringUtils.isNotEmpty(foWorkDOs.get(i).getAirworthinessAnnotationFlag())
                        &&!AirworthinessAnnotationFlagEnum.UN_MARK.getCode().equals(foWorkDOs.get(i).getAirworthinessAnnotationFlag()) ){
                    remark.append("PFP");
                    remark.append("\n");
                }
                if (StringUtils.isNotEmpty(foWorkDOs.get(i).getQualityAnnotationFlag())
                        &&!QualityAnnotationFlagEnum.UN_MARK.getCode().equals(foWorkDOs.get(i).getQualityAnnotationFlag()) ){
                    remark.append("试模");
                    remark.append("\n");
                }

                visualDTO.setRemarks(remark.toString());
                visualDTOList.add(visualDTO);
                //热处理工序；
                // 判断当前工序是否411 工序
                if (CommonConstant.DEPT_411.equals(foWorkDOs.get(i).getDept())){
                    HeatWorkDTO heatWorkDTO = new HeatWorkDTO();
                    heatWorkDTO.setWorkNo(foWorkDOs.get(i).getSequence());
                    heatWorkDTO.setWorkInstruction(foWorkDOs.get(i).getWorkInstruction());
                    // 所需工装
                    List<FoToolDTO> foRequiredToolDOList = foWorkDOs.get(i).getFoToolList();
                    StringBuffer foRequiredTools = new StringBuffer();
                    if (foRequiredToolDOList!=null && foRequiredToolDOList.size()>0){
                        for (int j = 0; j <foRequiredToolDOList.size() ; j++) {
                            foRequiredTools.append(foRequiredToolDOList.get(j).getToolNumber());
                            foRequiredTools.append("\n");
                        }
                        heatWorkDTO.setFoRequiredTools(foRequiredTools.toString());
                    }
                    heatWorkList.add(heatWorkDTO);
                    hotFlg=true;
                } if (hotFlg){
                    if (CommonConstant.DEPT_280.equals(foWorkDOs.get(i).getDept())){
                        HeatWorkDTO heatWorkDTO = new HeatWorkDTO();
                        // 可选工序
                        if (!CommonConstant.LINE_THROUGH.equals(foWorkDOs.get(i).getOptionalInstruction())){
                            heatWorkDTO.setWorkNo(foWorkDOs.get(i).getSequence()+CommonConstant.LINE_THROUGH +foWorkDOs.get(i).getOptionalInstruction());
                        } else {
                            heatWorkDTO.setWorkNo(foWorkDOs.get(i).getSequence());
                        }
                        heatWorkDTO.setWorkInstruction(foWorkDOs.get(i).getWorkInstruction());
                        // 所需工装
                        List<FoToolDTO> foRequiredToolDOList = foWorkDOs.get(i).getFoToolList();
                        StringBuffer foRequiredTools = new StringBuffer();
                        if (foRequiredToolDOList!=null && foRequiredToolDOList.size()>0){
                            for (int j = 0; j <foRequiredToolDOList.size() ; j++) {
                                foRequiredTools.append(foRequiredToolDOList.get(j).getToolNumber());
                                foRequiredTools.append("\n");
                            }
                            heatWorkDTO.setFoRequiredTools(foRequiredTools.toString());
                        }
                        List<FoAttachmentDTO> foAttachmentList = foWorkDOs.get(i).getFoAttachmentList();
                        if (CollectionUtil.isNotEmpty(foAttachmentList)){
                            heatWorkDTO.setAttachments(IMAGE_HEAD+ ImageUtils.image2Base64(foAttachmentList.get(0).getUrl()));
                        }
                        heatWorkList.add(heatWorkDTO);
                    }
                }
            }
        }
        //按照工序号升序
        Comparator bya = Comparator.comparing(VisualDTO::getWorkNo);
        Comparator hya = Comparator.comparing(HeatWorkDTO::getWorkNo);
        Collections.sort(visualDTOList,bya);
        Collections.sort(heatWorkList,hya);
        List<VisualDTO> visualDTOList1 = new ArrayList<>();
        List<VisualDTO> visualDTOList2 = new ArrayList<>();
        if (visualDTOList!=null && visualDTOList.size()>0){
            int cont = visualDTOList.size()/2;
            int contA = visualDTOList.size()%2;
            for (int i = 0; i < visualDTOList.size(); i++) {
                if (contA>0){
                    if (i<=cont){
                        visualDTOList1.add(visualDTOList.get(i));
                    } else {
                        visualDTOList2.add(visualDTOList.get(i));
                    }
                } else {
                    if (i<cont){
                        visualDTOList1.add(visualDTOList.get(i));
                    } else {
                        visualDTOList2.add(visualDTOList.get(i));
                    }
                }
            }
             if (contA>0){
                 visualDTOList2.add(new VisualDTO());
             }
        }
        followSheetDTO.setVisualList(visualDTOList1);
        followSheetDTO.setVisualList2(visualDTOList2);
        List<VisualAllDTO> listAll = new ArrayList<>();
        if (visualDTOList1!=null && visualDTOList1.size()>0 ){
            for (int i = 0; i < visualDTOList1.size(); i++) {
                VisualAllDTO  visualAllDTO= new VisualAllDTO();
                visualAllDTO.setWorkNo(visualDTOList1.get(i).getWorkNo());
                visualAllDTO.setStatus(visualDTOList1.get(i).getStatus());
                visualAllDTO.setRemarks(visualDTOList1.get(i).getRemarks());
                visualAllDTO.setWorkRemarks(visualDTOList1.get(i).getWorkRemarks());
                visualAllDTO.setWorkNo2(visualDTOList2.get(i).getWorkNo());
                visualAllDTO.setStatus2(visualDTOList2.get(i).getStatus());
                visualAllDTO.setRemarks2(visualDTOList2.get(i).getRemarks());
                visualAllDTO.setWorkRemarks2(visualDTOList2.get(i).getWorkRemarks());
                listAll.add(visualAllDTO);
            }
        }
        followSheetDTO.setVisualListAll(listAll);
        followSheetDTO.setHeatWorkList(heatWorkList);
         // 生成二维码
        String qrcodeUrl= QrCodeUtil.generateAsBase64(foSourceDTO.getPartNo()+" "+foSourceDTO.getSerNo()+"" +foSourceDTO.getQty(), new QrConfig(100,100) ,"jpg");
        followSheetDTO.setQrCode(qrcodeUrl);
        // 生成条形码
        BufferedImage bufferedImage =QrCodeUtil.generate(foSourceDTO.getSerNo(), BarcodeFormat.CODE_128 , new QrConfig(350,80) );
        String barCodeUrl = ImgUtil.toBase64DataUri(bufferedImage, "jpg");
        followSheetDTO.setBarCode(barCodeUrl);
        if (foSourceDTO.getDmirFlag()!=null && foSourceDTO.getDmirFlag()>0){
            followSheetDTO.setDmir(foFileOperateUtil.getImageBase64("AAD.png"));
        }

        if (foSourceDTO.getFaiFlag()!=null && foSourceDTO.getFaiFlag()>0 ){
            followSheetDTO.setFai(foFileOperateUtil.getImageBase64("SJ.png"));
        }

        if (foSourceDTO.getPfpFlag()!=null && foSourceDTO.getPfpFlag()){
            followSheetDTO.setPfp(foFileOperateUtil.getImageBase64("PFP.png"));
        }
        if (foSourceDTO.getTestModeFlag()!=null &&foSourceDTO.getTestModeFlag()){
            followSheetDTO.setTestModel(foFileOperateUtil.getImageBase64("SM.png"));
        }

        if (FoStatusEnum.TO_BE_TREATED_PROJECT.getCode().equals(foSourceDTO.getStatus())){
            followSheetDTO.setFrr(foFileOperateUtil.getImageBase64("FRR.png"));
        }
        return SingleResponse.of(foFileOperateUtil.exportToFile(followSheetDTO,mpUrl,"",""));
    }

}
